# 使用userlib爬取有道翻译的信息
from urllib import request, parse
import json


def fanyi(keyword):
    # 定义请求URL地址和参数
    url = "http://fanyi.youdao.com/translate?s" \
          "martresult=dict&smartresult=rule"
    data = {
        'i': keyword,
        'from': 'AUTO',
        'to': 'AUTO',
        'smartresult': 'dict',
        'client': 'fanyideskweb',
        'salt': '1532941171785',
        'sign': '6fdf4ca3a4cf1d059739e7fbe9bf371f',
        'doctype': 'json',
        'version': '2.1',
        'keyfrom': 'fanyi.web',
        'action': 'FY_BY_REALTIME',
        'typoResult': 'false',
    }

    data = parse.urlencode(data)

    headers = {
        'Accept': 'application/json,text/javascript,*/*;q=0.01',
        'Accept-Encoding': 'deflate',
        'Accept-Language': 'zh-CN,zh;q=0.9,zh-TW;q=0.8,fr;q=0.7,en;q=0.6',
        'Connection': 'keep-alive',
        'Content-Length': str(len(data)),
        'Content-Type': 'application/x-www-form-urlencoded;charset = UTF-8',
        'Cookie': 'OUTFOX_SEARCH_USER_ID=-787874842@61.148.242.122;'
                  'P_INFO=m18514691842@163.com|1520212841|2|163|00&99|n'
                  'ull&null&null#bej&null#10#0#0|185842&1||18514691842@16'
                  '3.com; JSESSIONID=aaaY4MsTBRB-ggCz_7Ptw;OUTFOX_SEARCH_US'
                  'ER_ID_NCOO=1393405064.9475212;__rl__test__cookies=153'
                  '2933599073',
        'Host': 'fanyi.youdao.com',
        'Origin': 'http://fanyi.youdao.com',
        'Referer': 'http://fanyi.youdao.com/',
        'User - Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) Apple'
                        'WebKit/537.36 (KHTML, likeGecko) Chrome/67.0.3'
                        '396.99 Safari/537.36',
        'X - Requested - With': 'XMLHttpRequest',
    }

    # 发送请求，爬取信息
    req = request.Request(url, data=bytes(data, encoding="utf-8"),
                          headers=headers)
    res = request.urlopen(req)

    # 解析结果
    str_json = res.read().decode("utf-8")
    # print(str_json)
    myjson = json.loads(str_json)

    print(myjson['translateResult'][0][0]['tgt'])


# 主程序
if __name__ == '__main__':
    while True:
        keyword = input("请输入要翻译词：")
        if keyword == 'q':
            break
        fanyi(keyword)
